/**
 * 数据迁移脚本
 * 将模拟数据迁移到 MongoDB 数据库
 */

import { mongoDB, HospitalData, DepartmentData, EquipmentData, AlertData, PatientFlowData, KPIData, POIData } from './mongodb'
import { hospitalData, generateRealisticAlerts, generatePatientFlowData, generateDepartmentData, generateEquipmentData, realDataService } from './realData'

export class DataMigrationService {
  private hospitalId: string = ''

  /**
   * 执行完整的数据迁移
   */
  async migrateAllData(): Promise<void> {
    try {
      console.log('🚀 开始数据迁移...')

      // 连接数据库
      await mongoDB.connect()

      // 创建索引
      await mongoDB.createIndexes()

      // 清空现有数据（可选）
      await this.clearExistingData()

      // 迁移医院基础数据
      await this.migrateHospitalData()

      // 迁移科室数据
      await this.migrateDepartmentData()

      // 迁移设备数据
      await this.migrateEquipmentData()

      // 迁移告警数据
      await this.migrateAlertData()

      // 迁移患者流量数据
      await this.migratePatientFlowData()

      // 迁移KPI数据
      await this.migrateKPIData()

      // 迁移POI数据
      await this.migratePOIData()

      console.log('✅ 数据迁移完成！')

    } catch (error) {
      console.error('❌ 数据迁移失败:', error)
      throw error
    } finally {
      // 断开数据库连接
      await mongoDB.disconnect()
    }
  }

  /**
   * 清空现有数据
   */
  private async clearExistingData(): Promise<void> {
    console.log('🧹 清空现有数据...')

    const collections = [
      'hospitals',
      'departments',
      'equipment',
      'alerts',
      'patient_flow',
      'kpis',
      'pois'
    ]

    for (const collection of collections) {
      await mongoDB.clearCollection(collection)
    }

    console.log('✅ 现有数据已清空')
  }

  /**
   * 迁移医院基础数据
   */
  private async migrateHospitalData(): Promise<void> {
    console.log('🏥 迁移医院基础数据...')

    const hospital: Omit<HospitalData, '_id' | 'id' | 'createdAt' | 'updatedAt'> = {
      name: hospitalData.info.name,
      level: hospitalData.info.level,
      address: hospitalData.info.address,
      phone: hospitalData.info.phone,
      totalBeds: hospitalData.info.totalBeds,
      dailyCapacity: hospitalData.info.dailyCapacity,
      founded: hospitalData.info.founded,
      staff: hospitalData.info.staff,
      center: [120.1551, 30.2741], // 杭州市第一人民医院坐标
      bounds: {
        north: 30.2751,
        south: 30.2731,
        east: 120.1561,
        west: 120.1541
      },
      metadata: {
        source: 'migration',
        version: '1.0'
      }
    }

    const result = await mongoDB.addHospital(hospital)
    this.hospitalId = result.id

    console.log(`✅ 医院数据迁移完成: ${result.name} (ID: ${result.id})`)
  }

  /**
   * 迁移科室数据
   */
  private async migrateDepartmentData(): Promise<void> {
    console.log('🏢 迁移科室数据...')

    const departments = hospitalData.departments.map(dept => ({
      hospitalId: this.hospitalId,
      name: dept.name,
      type: this.mapDepartmentType(dept.id),
      floor: dept.floor,
      capacity: dept.capacity,
      director: dept.director,
      phone: dept.phone,
      position: this.generateDepartmentPosition(dept.floor),
      status: 'active' as const,
      metadata: {
        source: 'migration',
        originalId: dept.id
      }
    }))

    for (const dept of departments) {
      await mongoDB.addDepartment(dept)
    }

    console.log(`✅ 科室数据迁移完成: ${departments.length} 个科室`)
  }

  /**
   * 迁移设备数据
   */
  private async migrateEquipmentData(): Promise<void> {
    console.log('🔬 迁移设备数据...')

    const equipment = hospitalData.equipment.map(equip => ({
      hospitalId: this.hospitalId,
      name: equip.name,
      type: this.mapEquipmentType(equip.type),
      location: equip.location,
      status: equip.status as 'running' | 'idle' | 'maintenance' | 'busy',
      uptime: parseFloat(equip.uptime.replace('%', '')),
      currentUtilization: Math.floor(Math.random() * 100),
      maintenance: {
        lastDate: new Date(equip.maintenance),
        nextDate: new Date(new Date(equip.maintenance).getTime() + 30 * 24 * 60 * 60 * 1000),
        status: 'scheduled' as const
      },
      specifications: {
        manufacturer: this.getManufacturer(equip.type),
        model: `${equip.type}-${equip.name}`,
        year: 2018 + Math.floor(Math.random() * 6)
      },
      metadata: {
        source: 'migration',
        originalId: equip.id
      }
    }))

    for (const equip of equipment) {
      await mongoDB.addEquipment(equip)
    }

    console.log(`✅ 设备数据迁移完成: ${equipment.length} 台设备`)
  }

  /**
   * 迁移告警数据
   */
  private async migrateAlertData(): Promise<void> {
    console.log('⚠️ 迁移告警数据...')

    const alerts = generateRealisticAlerts().map(alert => ({
      hospitalId: this.hospitalId,
      type: alert.type as 'crowding' | 'equipment' | 'environment' | 'supply' | 'traffic',
      severity: alert.severity as 'low' | 'medium' | 'high' | 'critical',
      title: alert.title,
      location: alert.location,
      description: alert.description,
      timestamp: new Date(alert.timestamp),
      status: alert.status as 'active' | 'in_progress' | 'pending' | 'monitoring' | 'resolved',
      assignee: alert.assignee,
      estimatedResolution: alert.estimatedResolution,
      impact: alert.impact,
      metadata: {
        source: 'migration',
        originalId: alert.id
      }
    }))

    for (const alert of alerts) {
      await mongoDB.addAlert(alert)
    }

    console.log(`✅ 告警数据迁移完成: ${alerts.length} 条告警`)
  }

  /**
   * 迁移患者流量数据
   */
  private async migratePatientFlowData(): Promise<void> {
    console.log('👥 迁移患者流量数据...')

    const today = new Date()
    const patientFlowData = generatePatientFlowData()

    const flows = patientFlowData.map(flow => ({
      hospitalId: this.hospitalId,
      hour: flow.hour,
      time: flow.time,
      patients: flow.patients,
      emergency: flow.emergency,
      outpatient: flow.outpatient,
      inpatient: flow.inpatient,
      date: today,
      metadata: {
        source: 'migration',
        isWeekend: flow.hour >= 0 && flow.hour <= 6 ? true : false
      }
    }))

    for (const flow of flows) {
      await mongoDB.addPatientFlow(flow)
    }

    console.log(`✅ 患者流量数据迁移完成: ${flows.length} 条记录`)
  }

  /**
   * 迁移KPI数据
   */
  private async migrateKPIData(): Promise<void> {
    console.log('📊 迁移KPI数据...')

    const realTimeData = realDataService.getAllRealTimeData()
    const kpis = Object.entries(realTimeData.kpis).map(([metric, data]) => ({
      hospitalId: this.hospitalId,
      metric: metric as 'bedUtilization' | 'patientFlow' | 'equipmentEfficiency' | 'patientSatisfaction' | 'emergencyResponse' | 'averageWaitTime',
      value: data.value,
      target: data.target,
      trend: data.trend,
      status: data.status as 'excellent' | 'good' | 'warning' | 'critical',
      timestamp: new Date(),
      metadata: {
        source: 'migration',
        lastUpdate: data.lastUpdate
      }
    }))

    for (const kpi of kpis) {
      await mongoDB.addKPI(kpi)
    }

    console.log(`✅ KPI数据迁移完成: ${kpis.length} 个指标`)
  }

  /**
   * 迁移POI数据
   */
  private async migratePOIData(): Promise<void> {
    console.log('📍 迁移POI数据...')

    // 基于科室数据生成POI
    const departments = hospitalData.departments
    const pois = departments.map(dept => ({
      hospitalId: this.hospitalId,
      name: dept.name,
      type: this.mapPOIType(dept.id),
      position: this.generateDepartmentPosition(dept.floor),
      floor: dept.floor,
      description: `${dept.name} - ${dept.director}负责`,
      capacity: dept.capacity,
      status: 'active' as const,
      metadata: {
        source: 'migration',
        departmentId: dept.id,
        director: dept.director,
        phone: dept.phone
      }
    }))

    for (const poi of pois) {
      await mongoDB.addPOI(poi)
    }

    console.log(`✅ POI数据迁移完成: ${pois.length} 个点位`)
  }

  /**
   * 映射科室类型
   */
  private mapDepartmentType(deptId: string): DepartmentData['type'] {
    const typeMap: Record<string, DepartmentData['type']> = {
      'emergency': 'emergency',
      'internal': 'outpatient',
      'surgery': 'surgery',
      'pediatrics': 'outpatient',
      'obstetrics': 'outpatient',
      'ophthalmology': 'outpatient',
      'ent': 'outpatient',
      'dermatology': 'outpatient',
      'cardiology': 'outpatient',
      'neurology': 'outpatient',
      'icu': 'inpatient',
      'or': 'surgery'
    }
    return typeMap[deptId] || 'outpatient'
  }

  /**
   * 映射设备类型
   */
  private mapEquipmentType(type: string): EquipmentData['type'] {
    const typeMap: Record<string, EquipmentData['type']> = {
      'MRI': 'mri',
      'CT': 'ct',
      'X-Ray': 'xray',
      'Ultrasound': 'ultrasound',
      'Ventilator': 'ventilator',
      'Surgery': 'bed',
      'Dialysis': 'bed',
      'Monitor': 'bed'
    }
    return typeMap[type] || 'bed'
  }

  /**
   * 映射POI类型
   */
  private mapPOIType(deptId: string): POIData['type'] {
    const typeMap: Record<string, POIData['type']> = {
      'emergency': 'emergency',
      'internal': 'department',
      'surgery': 'department',
      'pediatrics': 'department',
      'obstetrics': 'department',
      'ophthalmology': 'department',
      'ent': 'department',
      'dermatology': 'department',
      'cardiology': 'department',
      'neurology': 'department',
      'icu': 'department',
      'or': 'department'
    }
    return typeMap[deptId] || 'department'
  }

  /**
   * 生成科室位置
   */
  private generateDepartmentPosition(floor: string): [number, number] {
    const baseLng = 120.1551
    const baseLat = 30.2741

    // 根据楼层生成不同的位置
    const floorOffset = parseInt(floor.replace('L', '')) * 0.0001
    const randomOffset = (Math.random() - 0.5) * 0.0002

    return [
      baseLng + randomOffset,
      baseLat + floorOffset + randomOffset
    ]
  }

  /**
   * 获取设备制造商
   */
  private getManufacturer(type: string): string {
    const manufacturers = ['西门子', '飞利浦', 'GE', '东软', '迈瑞']
    return manufacturers[Math.floor(Math.random() * manufacturers.length)]
  }
}

// 创建迁移服务实例
export const dataMigration = new DataMigrationService()

// 导出便捷方法
export const migrateMockDataToMongoDB = () => dataMigration.migrateAllData()

export default dataMigration
